#-*-coding:utf-8-*-
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response


def dosql (request):
    #return HttpResponse('xx')
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    err={}
    ok=''
    if request.POST:
        sqlstr=request.POST.get('sqlstr','')
        password=request.POST.get('password','')
        from django.db import connection
        cursor=connection.cursor()
        if password=='okgo' and 'select' not in sqlstr:
            cursor.execute("%s"%sqlstr)
            ok='执行:'+str(sqlstr)+" 成功"
        else:
            ok='密码不正确'
        colstable=''
        if 'select' in sqlstr and '*' not in sqlstr :
            cursor.execute("%s"%sqlstr)
            ok='执行:'+str(sqlstr)+" 成功"
            tus=cursor.fetchall()
            bs=sqlstr.find('from')
            colstr=sqlstr[len('seletc'):(bs-1)].strip()
            cols_list=colstr.split(",")
            colstable+="<br><table border=1 >"
            colstable+="<tr><td class='tdbgl' width='20px;'>rows</td>"
            for col in cols_list:
                colstable+="<td class='tdbgl'>"+str(col)+"</td>"
            colstable+="</tr>"
            #ok+='<br>'+str(cols_list)
            i=0
            for tu in tus:
                colstable+="<tr><td>"+str(i)+"</td>"
                j=0
                for col in cols_list:
                    colvar=str(col)
                    colstable+="<td>"+str(tu[j])+"</td>"
                    j=j+1
                colstable+="</tr>"
                i=i+1
            ok+='<br>列数：'+str(len(cols_list))+'行数:'+str(len(tus))
            ok+='<br>'+colstable

    return render_to_response('sql.html',{'err':err,'ok':ok})



